package com.wyh.edu.service.impl;

import com.wyh.edu.dao.AuthCodeDao;
import com.wyh.edu.pojo.AuthCode;
import com.wyh.edu.service.AuthCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author wuyuhan
 * @date 2021/2/4 23:58
 */
@Service
public class AuthCodeServiceImpl implements AuthCodeService {
    @Autowired
    private AuthCodeDao authCodeDao;

    @Value("${config.code.validate.expire}")
    private int codeExpireSeconds;

    @Override
    public void createAuthCode(String email, String code) {

        long createTime = System.currentTimeMillis();
        long expireTime = createTime + codeExpireSeconds * 1000;

        AuthCode lagouAuthCode = new AuthCode();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCode(code);
        lagouAuthCode.setCreatetime(new Date(createTime));
        lagouAuthCode.setExpiretime(new Date(expireTime));

        authCodeDao.save(lagouAuthCode);

    }

    @Override
    public int validateAuthCode(String email, String code) {

        AuthCode latest = authCodeDao.findFirstByEmailOrderByIdDesc(email);
        //0-正确，1-错误，2-超时
        if (latest == null){
            return 1;
        }
        if (!latest.getCode().equalsIgnoreCase(code)){
            return 1;
        }

        long expireTime = latest.getExpiretime().getTime();
        if (expireTime <= System.currentTimeMillis()){
            return 2;
        }
        return 0;
    }
}
